Error trapping for a missing data source in a Spring MVC / Spring JDBC web app [migrated]

Posted by Geeb on Programmers See other posts from Programmers or by Geeb
Published on 2012-04-02T13:21:52Z Indexed on 2012/04/02 17:41 UTC
Read the original article Hit count: 597

Filed under:
|
|
|
|

I have written a web app that uses Spring MVC libraries and Spring JDBC to connect to an Oracle DB. (I don't use any ORM type libraries as I create stored procedures on Oracle that do my stuff and I'm quite happy with that.) I use a connection pool to Oracle managed by the Tomcat container

The app generally works absolutely fine by the way!

BUT... I noticed the other day when I tried to set up the app on another Tomcat instance that I had forgotten to configure the connection pool and obviously the app could not get hold of an org.apache.commons.dbcp.BasicDataSource object, so it crashed.

I define the pool params in the tomcat "context.conf"

In my "web.xml" I have:

<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/Spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <!-- Map *everything* to appServlet -->
    <url-pattern>/</url-pattern>
</servlet-mapping>

<resource-ref>
    <description>Oracle Datasource example</description>
    <res-ref-name>jdbc/ora1</res-ref-name>
    <res-type>org.apache.commons.dbcp.BasicDataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

And I have a Spring "servlet-context.xml" where JNDI is used to map the data source object provided by the connection pool to a Spring bean with the ID of "dataSource":

<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/ora1"
    resource-ref="true" />

Here's the question: Where do I trap the case where the database cannot be accessed for whatever reason?

I don't want the user to see a yard-and-a-half of Java stack trace in their browser, rather a nicer message that tells them there is a database problem etc. It seems that my app tries to configure the "dataSource" bean (in "servlet-context.xml") before any code has tested it can actually provide a dataSource object from the pool?!

Maybe I'm not fully understanding exactly what is going on in these stages of the app firing up ...

Thanks for any advice!

© Programmers or respective owner

Related posts about java

Related posts about mvc